package com.woniuxy.filter;

import com.alibaba.nacos.common.utils.JacksonUtils;
import com.woniuxy.remote.RemoteAuthService;
import com.woniuxy.utils.ResultVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器，用户身份认证
 */
@Component
public class AuthGlobalFilter implements GlobalFilter,Ordered {

    @Autowired
    private RemoteAuthService remoteAuthService;

    /**
     * 过滤器逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().toString();
        if(path.contains("/customer-serv/order/notify") || path.contains("/customer-serv/order/success") || path.contains("/auth-serv/auth/login") || path.contains("/auth-serv/auth/register") ||path.contains("/auth-serv/customer/logout")) {//登录、注册请求
            return chain.filter(exchange);
        }
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)) {//token为空
            return getResultVO(exchange);
        }
        ResultVO check = remoteAuthService.check(token);
        if(check.getCode() == HttpStatus.INTERNAL_SERVER_ERROR.value()) {//token无效
            return getResultVO(exchange);
        }
        return chain.filter(exchange);
    }

    /**
     * 认证不通过响应信息
     * @param exchange
     * @return
     */
    private Mono<Void> getResultVO(ServerWebExchange exchange){
        ResultVO resultVO = ResultVO.fail(HttpStatus.UNAUTHORIZED.value(), "认证不通过");
        byte[] bytes = JacksonUtils.toJsonBytes(resultVO);
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
        return exchange.getResponse().writeWith(Mono.just(buffer));
    }

    /**
     * 标识当前过滤器的优先级，返回的数字越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }
}
